package com.bifang.common.util;

import com.bifang.common.constant.CacheConst;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

/***
 * 服务请求相关工具类
 * @author chenzh
 * @date 2018-08-15
 * */
public class ServiceRequestUtil {
    public static String getAccessToken(HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getHeader(CacheConst.ACCESS_TOKEN);
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getParameter(CacheConst.ACCESS_TOKEN);
        }
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getHeader(CacheConst.ACCESS_TOKEN.toLowerCase());
        }
        if (accessToken == null && request.getCookies() != null) {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (CacheConst.ACCESS_TOKEN.equals(cookie.getName())) {
                    accessToken = cookie.getValue();
                    return accessToken;
                }
            }
        }
        // 重置cookie
        if (response != null) {
            if (request.getCookies() != null) {
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    String cookieAccessToken = "";
                    if (CacheConst.ACCESS_TOKEN.equals(cookie.getName())) {
                        cookieAccessToken = cookie.getValue();
                        cookie.setMaxAge(0);
                        // 每次获取cookie都重置设置cookie替代掉
                        Cookie newCookie = new Cookie(CacheConst.ACCESS_TOKEN, cookieAccessToken);
                        newCookie.setPath("/");
                        newCookie.setMaxAge(21600);
                        String protocol = request.getScheme();
                        if ("https".equals(protocol)) {
                            // 仅适用于https的环境
                            newCookie.setSecure(true);
                        } else {
                            newCookie.setHttpOnly(true);
                        }
                        response.addCookie(newCookie);
                    }
                }
            }
        }
        return accessToken;
    }
    /**
     * 获取本地IP地址
     *
     * @throws SocketException
     */
    public static String getLocalIP() throws UnknownHostException, SocketException {
        if (isWindowsOS()) {
            return InetAddress.getLocalHost().getHostAddress();
        } else {
            return getLinuxLocalIp();
        }
    }

    /**
     * 判断操作系统是否是Windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /** 获取本地Host名称 */
    public static String getLocalHostName() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostName();
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp() throws SocketException {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
                    en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                            enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::")
                                    && !ipaddress.contains("0:0:")
                                    && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                                System.out.println(ipaddress);
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            System.out.println("获取ip地址异常");
            ip = "127.0.0.1";
            ex.printStackTrace();
        }
        return ip;
    }
}
